//监听数据
class Watcher {
  constructor(vm, exp, cb) {
    this.vm = vm;
    this.exp = exp;
    this.cb = cb;
    this.value = this.get();

    /**
     * console.log(vm);
     * {
     *   message: "Hello World", 
     *   color: color: {red: "#123334", orange: "#333344"}
     * }
     */

    // console.log(this.exp);
    //message/color

    // console.log(this.cb);
    //()=>{updateFn && updateFn(node, this.getVal(vm, exp));}

    // console.log(this.value);
    //Hello World! / #123334
  }

  get() {
    //将watcher实例对象赋值给Dep
    Dep.target = this;
    let value = this.getValue(this.vm, this.exp);
    Dep.target = null;
    return value;
  }

  getValue(vm, exp) {
    //message.a.b.c => [message, a, b, c]
    exp = exp.split('.');
    // console.log(exp);
    //["message"]
    //["color", "red"]

    //归纳解决多层对象数据嵌套的问题
    //累加器prev/vm.$data
    //当前项next

    /**
     * console.log(vm);
     * {
     *   message: "Hello World", 
     *   color: color: {red: "#123334", orange: "#333344"}
     * }
     */

    return exp.reduce((prev, next) => {
      // console.log(next); message/color/red
      // console.log(prev[next]); 
      // Hello World / { red: "#123334", orange: "#333344" } /#123334
      return prev[next];
    }, vm);
  }

  update() {
    let newValue = this.getValue(this.vm, this.exp);
    let oldValue = this.value;
    if (newValue !== oldValue) {
      this.cb(newValue);
    }
  }
}